<script setup lang="ts">
import { useWatcher } from '@sa/alova/client';
import { ref, watch } from 'vue';
import { alova } from '@/service/request';

defineOptions({
  name: 'PorDictTag'
});

interface Props {
  dictCode?: string;
  valueToNumber?: boolean;
  valueToBool?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  dictCode: undefined,
  value: undefined,
  valueToNumber: false,
  valueToBool: false
});

const value = defineModel<string | number | boolean>('value', { required: true });

type colorType = 'default' | 'error' | 'primary' | 'info' | 'success' | 'warning';

const empty = {
  label: '',
  value: '',
  colorType: 'default' as colorType
};

const tag = ref(empty);
const getDictItems = (dictCode: string | undefined) => {
  return alova.Get<Record<string, string>[]>(`/setting/dictItem/simpleList`, { params: { dictCode } });
};

const dictCode = ref(props.dictCode || '');
watch(
  () => props.dictCode,
  (newDictCode: string | undefined) => {
    dictCode.value = newDictCode || '';
  }
);

const { loading } = useWatcher(() => getDictItems(dictCode.value), [dictCode, value], {
  immediate: true,
  debounce: [0, 0]
}).onSuccess(({ data }) => {
  const findMatchingItem = () => {
    if (props.valueToNumber) {
      const tmpValue = value.value === null ? 0 : Number(value.value);
      return data.find(item => String(item.value) === String(tmpValue));
    }

    if (props.valueToBool) {
      const tmpValue = value.value === null ? false : Boolean(value.value);

      return data.find(item => String(item.value) === String(tmpValue));
    }

    return data.find(item => String(item.value) === String(value.value));
  };

  const dicItem = findMatchingItem();
  tag.value = dicItem
    ? {
        label: dicItem.name,
        value: dicItem.value,
        colorType: dicItem.colorType as colorType
      }
    : empty;
});
</script>

<template>
  <NRadioGroup>
    <NTag :type="tag.colorType" :loading="loading">{{ tag.label }}</NTag>
  </NRadioGroup>
</template>

<style scoped></style>
